package com.my.ext.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.my.ext.entity.Admin;
import com.my.ext.service.IAdminService;
import com.my.ext.utils.ResultObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/admin")
@Api("管理员接口接口API")
public class AdminController {

	@Autowired
	IAdminService service;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation(value = "登录接口", notes = "管理员登录过程")
	public String login(Admin admin) {
		Subject sub = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(admin.getAccount(), admin.getAuthcstring());
		ResultObject obj = new ResultObject();
		try {
			if(sub.isAuthenticated()) {
				sub.logout();
			}
			sub.login(token);
			obj.setStatus(1);
			obj.setInfo("success");
			return "redirect:../index.html";
		}catch (Exception e) {
			e.printStackTrace();
			obj.setStatus(0);
			obj.setInfo("error");
			return "redirect:../login.html";
		}
		
	}
	
	@RequestMapping(value="/querySelf", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	@RequiresAuthentication
	public ResultObject querySelfName() {
		Admin admin = (Admin)SecurityUtils.getSubject().getPrincipal();
		ResultObject obj = new ResultObject();
		obj.setStatus(1);
		obj.setData(admin.getAccount());
		
		return obj;
		
		
	}

	@RequestMapping(value="/queryrole",method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public ResultObject queryrole() {
		Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
		ResultObject obj = new ResultObject();
		obj.setStatus(1);
		obj.setData(admin.getLevel());
		return obj;
	}

	@RequestMapping(value="/queryAll",method = {RequestMethod.GET, RequestMethod.POST})
	@RequiresAuthentication
	@ResponseBody
	public ResultObject queryAdmin(int page, int size) {
		ResultObject obj = new ResultObject();
		obj.setStatus(1);
		obj.setData(service.findAll(page, size));
		return obj;
	}
	
}
